﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml;
using System.Xml.Linq;
using iTextSharp.text.pdf;

namespace pdf2xfa_dotnet
{
    /// <summary>
    /// pdf2xfa allows remote users to upload a PDF file and returns the XFA embedded in it, if any.
    /// </summary>
    [WebService(Namespace = "http://pdf2xfa.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class pdf2xfa : System.Web.Services.WebService
    {
        [WebMethod]
        public XmlElement ExtractXFA(byte[] pdfFile)
        {
            PdfReader reader = new PdfReader(pdfFile);
            XfaForm xfa = new XfaForm(reader);


            XDocument document = xfa.DomDocument.ToXDocument();
            // WCF services don't like processing instructions, remove them.
            var instructions = document.DescendantNodes().Where(n=>n.NodeType == XmlNodeType.ProcessingInstruction);
            
            foreach (var instruction in instructions.ToList())
            {
                instruction.Remove();
            }

            return document.ToXmlDocument().DocumentElement;
        }
    }

    public static class DocumentExtensions
    {
        public static XmlDocument ToXmlDocument(this XDocument document)
        {
            var result = new XmlDocument();
            result.Load(document.CreateReader());
            return result;
        }

        public static XDocument ToXDocument(this XmlDocument xmlDocument)
        {
            return XDocument.Load(new XmlNodeReader(xmlDocument));
        }
    }
}